#ifndef EVENTANALYZER_H
#define EVENTANALYZER_H

#include <QObject>
#include "satellitepos.h"
#include "observer.h"

struct SatelliteEvent {
    int centerFreq; // 中心频率（如9600）
    int noradId;        // 卫星NORAD ID
    QDateTime startTime;
    QDateTime endTime;
    double maxElevation;
};

struct EventData {
    int centerFreq; // 中心频率（如9600）
    QDateTime start;
    QDateTime end;
};

class EventAnalyzer : public QObject {
    Q_OBJECT
public:
    explicit EventAnalyzer(QObject *parent = nullptr,
                           const libsgp4::CoordGeodetic &observerGeo = libsgp4::CoordGeodetic(),
                           const QString &outputDir = "",
                           double minElevation = 5.0,//这里固定了最小仰角为5，时间步长为1，可以按要求修改，已拓展到UI控件
                           int timeStep = 1) :
        QObject(parent),
        m_observer(observerGeo.latitude,
                   observerGeo.longitude,
                   observerGeo.altitude),
        m_outputDir(outputDir),
        m_minElevation(minElevation),
        m_timeStepSec(timeStep),
        m_tleSource(SatellitePos::LocalFiles),  // 初始化默认值
        m_selectAllNorad(false)                // 初始化默认值
    {}

    void setAnalysisParams(QDateTime start, QDateTime end,
                           QString noradPath, QString tlePath,QString eventsPath,
                           SatellitePos::TleSource tleSource,
                           bool selectAll);

    // 解析CSV事件文件
    void parseCsvEvents(const QString& csvPath);

    // 设置事件文件路径
    void setEventsPath(const QString &path) { m_eventsPath = path; }

signals:
    void analysisFinished(bool success);
    void progressUpdated(int percent);

public slots:
    void startAnalysis();

private:
    // 核心事件检测逻辑
    void detectSatelliteEvents(int centerFreq, int noradId,
                               const QDateTime& start, const QDateTime& end);

    // 保存结果到CSV
    void saveToCSV(const QMap<int, QList<SatelliteEvent>>& events);

private:
    SatellitePos::TleSource m_tleSource;  // 添加TLE来源模式
    bool m_selectAllNorad;                // 添加全选状态
    QString m_noradPath;                  // 添加NORAD路径存储
    QString m_tlePath;                     // 添加TLE路径存储
    QList<EventData> m_events;             // 存储CSV事件数据
    QString m_eventsPath;

    SatellitePos m_satPos;
    libsgp4::Observer m_observer;
    QDateTime m_startTime, m_endTime;
    QString m_outputDir;
    double m_minElevation;
    int m_timeStepSec;

    // 状态跟踪：key=centerFreq+NoradId，value=是否在过境中
    QMap<QPair<int, int>, bool> m_satelliteState;

    // 事件存储：key=centerFreq，value=该频率下的事件列表
    QMap<int, QList<SatelliteEvent>> m_allEvents;
};

#endif // EVENTANALYZER_H
